/**
 * Description：实测值录入 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.23
 */
const { reactive, ref } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
import { useExportExcel } from '../../../Scripts/hooks/useExportExcel.js'
const { ElMessage, ElMessageBox } = ElementPlus

export function useInputCheckResult() {
  const baseAPI = '../../../Ashx/InputCheckPointResultVue3PageHandler.ashx';

  const inputCheckResultDialogContainerTableRef = ref(null);//批次表格ref
  const inputCheckResultDialogChildContainerRef = ref(null);//子序号批次表格ref
  const inputCheckResultDialogCheckItemTableRef = ref(null);//检测项表格ref
  const inputCheckResultDialogCheckResultTableRef = ref(null);//检测项结果表格ref
  const importCheckResultUploadRef = ref(null);//检查项导入ref
  const fileUploadRef = ref(null);//文件上传ref

  let inputCheckResultObj = reactive({
    dialogVisible: false,
    tabObj: {
      container: 'container',
      checkitem: 'checkitem',
      childcontainer: 'childcontainer',
      checkresult: 'checkresult',
      inputZone: 'inputZone',
      importCheckPoint: 'importCheckPoint',
      uploadZone: 'uploadZone',
    },
    upload: {
      type: '公开'
    },
    currentSelectInfo: {},//当前选中的报工批次
    containerList: [],//批次信息表格
    checkitemList: [],//检测项表格
    childContainerList: [],//子批次表格
    checkItemResultList: [],//已录入结果表格
    checkResultImportfileList: [],//检测项导入的文件
    fileUploadList: [],//上传的文件
    fileUploadParams: {
      uploadType: '2',
      checkPointResult: [],
    },//文件上传额外附加的参数
  });
  let currentUserInfo = {};// 当前登录用户信息

  async function initInputCheckResultDialogData(selectionRows, userInfo) {
    inputCheckResultObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    await getContainerData(selectionRows);//查询批次报工信息
  }

  // 查询批次报工信息
  async function getContainerData(postData) {
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getContainerDataList`,
      data: { type: 'getContainerDataList', postData }
    });
    inputCheckResultObj.containerList = data.value.dtReportContainer;//流水卡信息表格
    inputCheckResultObj.childContainerList = data.value.dtChildContainer;//子批次表格
    inputCheckResultObj.currentSelectInfo = data.value.dtReportContainer[0];//【流水卡信息】表格默认选中第一行
    inputCheckResultDialogContainerTableRef.value.setCurrentRow(data.value.dtReportContainer[0]);//【流水卡信息】默认选中第一条(高亮显示)
  }

  // [流水卡信息]表格选中行变更
  async function handleCurrentChange(val) {
    if (!val) { return; }
    inputCheckResultObj.currentSelectInfo = val;
    const { containerid, workflowstepid, containerstepworkreportid, containertype } = inputCheckResultObj.currentSelectInfo;
    // 1.获取检测项
    await getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid: '' });
    if (containertype === 3) {
      // 2.查询报工时选择的子批次号
      inputCheckResultDialogChildContainerRef.value.clearSelection();//先清空选择
      // 过滤出报工时勾选的子批次，并选中
      const list = await getWorkreportChildContainer(containerstepworkreportid);
      inputCheckResultObj.childContainerList.forEach(row => {
        if (list.some(i => i.childcontainerid === row.childcontainerid)) {
          inputCheckResultDialogChildContainerRef.value.toggleRowSelection(row, undefined)
        }
      });
    }
  }

  // 查询单件带子序号报工时选择的子批次
  async function getWorkreportChildContainer(containerstepworkreportid) {
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getWorkreportChildContainer`,
      data: { type: 'getWorkreportChildContainer', containerstepworkreportid }
    });
    return data.value;
  }

  async function getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid }) {
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getCheckItemList`,
      data: {
        type: 'getCheckItemList',
        containerID: containerid,
        workFlowStepId: workflowstepid,
        containerStepWorkReportID: containerstepworkreportid,
        stepInfoID: stepinfoid,
      }
    });
    for (const i of data.value) {
      i.containerstepworkreportid = containerstepworkreportid;//缓存报工id
      i.containerid = containerid;//缓存批次id
      i.workflowstepid = workflowstepid;//缓存工序id
    }
    inputCheckResultObj.checkitemList = data.value;
  }

  // 检测项表格row点击事件
  function checkItemRowClick(row, column, event) {
    inputCheckResultDialogCheckItemTableRef.value.clearSelection();
    inputCheckResultDialogCheckItemTableRef.value.toggleRowSelection(row, undefined)
  }

  // 查询检测项录入结果
  async function getStepCheckPointResult(val) {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();
    if (selections.length !== 1) {
      inputCheckResultObj.checkItemResultList = [];
      return;
    }
    const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = selections[0];
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getStepCheckPointResult`,
      data: {
        type: 'getStepCheckPointResult',
        childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows(),//勾选的子批次
        stepCheckPointId: stepcheckpointid,//检查项id
        containerId: containerid,//批次id
        containerStepWorkReportID: containerstepworkreportid//报工id
      }
    });
    const reg = /^[+-]?\d+(\.\d+)?$/;//可选正负号开头，其余是合法的数字（含小数）
    for (const i of data.value) {
      // 使用replace方法替换匹配到的内容为空字符串
      const replaceReg = /^(&nbsp;)+|(&nbsp;)+$/g;
      let { basevalue, ceilfloat, floorfloat, workcheckpointresultnote, checkpointresultnote } = i;
      workcheckpointresultnote = workcheckpointresultnote ? workcheckpointresultnote.replace(replaceReg, '') : '';//移除工人录入实测值首尾的空格
      checkpointresultnote = checkpointresultnote ? checkpointresultnote.replace(replaceReg, '') : '';//移除检验录入实测值首尾的空格
      if (reg.test(basevalue) && reg.test(ceilfloat) && reg.test(floorfloat)) {
        let maxValue = parseFloat(basevalue) + parseFloat(ceilfloat);
        let minValue = parseFloat(basevalue) + parseFloat(floorfloat);
        if (reg.test(workcheckpointresultnote)) {
          let inputValue = parseFloat(workcheckpointresultnote);
          if (inputValue < minValue || inputValue > maxValue) {
            i.workerstatus = true;
          }
        }
        if (reg.test(checkpointresultnote)) {
          let inputValue = parseFloat(checkpointresultnote);
          if (inputValue < minValue || inputValue > maxValue) {
            i.checkerstatus = true;
          }
        }
      }
    }
    inputCheckResultObj.checkItemResultList = data.value;
    inputCheckResultDialogCheckResultTableRef.value.toggleAllSelection();//检测结果表格默认全选
  }

  // 获取检测项内容
  function getCheckItemValue() {
    const iframe = document.getElementById('inputCheckPointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    const innerHTML = elementInIframe.contentDocument.body.innerHTML;
    return innerHTML ? innerHTML.replace(/img/g, "IMG") : '';
  }

  // 清空检测项内容
  function clearCheckItemValue() {
    const iframe = document.getElementById('inputCheckPointContent');
    const elementInIframe = iframe.contentDocument.getElementById('wucToleranceInput1_ftbFinalHtml_designEditor');
    elementInIframe.contentDocument.body.innerHTML = "";
  }

  // 一键确认（复制工人检测内容）
  async function copyWorkerInputValue() {
    if (inputCheckResultObj.checkitemList.length === 0) {
      return ElMessage({ type: 'error', message: `批次没有检测项，不能一键确认`, grouping: true });
    }
    const { containerid, containerstepworkreportid, containertype, workflowstepid } = inputCheckResultObj.currentSelectInfo;
    // 一键确认前先校验
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=copyWorkerInputValidate`,
      data: { type: 'copyWorkerInputValidate', containerstepworkreportid }
    });

    if (data.value.length === 0) {
      return ElMessage({ type: 'error', message: `工人未录入实测值，不能一键确认`, grouping: true });
    }

    const worker = await getWorkerInputValues();//查询已录入实测值
    const overToleranceList = [];

    const reg = /^[+-]?\d+(\.\d+)?$/;//可选正负号开头，其余是合法的数字（含小数）
    for (const i of worker) {
      const replaceReg = /^(&nbsp;)+|(&nbsp;)+$/g;
      let { bubblenumber, basevalue, ceilfloat, floorfloat, workcheckpointresultnote } = i;
      workcheckpointresultnote = workcheckpointresultnote ? workcheckpointresultnote.replace(replaceReg, '') : '';//移除工人录入实测值首尾的空格
      if (reg.test(basevalue) && reg.test(ceilfloat) && reg.test(floorfloat) && reg.test(workcheckpointresultnote)) {
        let maxValue = parseFloat(basevalue) + parseFloat(ceilfloat);
        let minValue = parseFloat(basevalue) + parseFloat(floorfloat);
        let inputValue = parseFloat(workcheckpointresultnote);
        if (inputValue < minValue || inputValue > maxValue) {
          overToleranceList.push(bubblenumber);
        }
      }
    }

    if (overToleranceList.length > 0) {
      ElMessageBox.confirm(`气泡号：【${overToleranceList}】存在超差，是否继续一键确认`, '确认', { type: 'warning' }).then(async () => {
        const { data, status: { msg } } = await useFetch({
          url: `${baseAPI}?actions=copyWorkerInputResultValue`,
          data: {
            type: 'copyWorkerInputResultValue',
            containerId: containerid,
            containerStepWorkReportID: containerstepworkreportid,
            employeename: currentUserInfo.employeename
          }
        });
        if (data.value) {
          ElMessage({ type: 'success', message: `一键确认成功`, grouping: true });
          await getStepCheckPointResult();
        }
      }).catch(() => {
        ElMessage({ type: 'info', message: '已取消' });
      });
    } else {
      ElMessageBox.confirm(`你确认要将工人所录入的检测项内容一键复制给检验员吗?`, '确认', { type: 'warning' }).then(async () => {
        const { data, status: { msg } } = await useFetch({
          url: `${baseAPI}?actions=copyWorkerInputResultValue`,
          data: {
            type: 'copyWorkerInputResultValue',
            containerId: containerid,
            containerStepWorkReportID: containerstepworkreportid,
            employeename: currentUserInfo.employeename
          }
        });
        if (data.value) {
          ElMessage({ type: 'success', message: `一键确认成功`, grouping: true });
          if (containertype !== 3) {
            await getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid: '' })
          } else {
            await getStepCheckPointResult();
          }
        }
      }).catch(() => {
        ElMessage({ type: 'info', message: '已取消' });
      });
    }
  }

  // 判断输入的检测项是否超差
  function isOverTolerance() {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
    let content = getCheckItemValue();//录入的检测项
    content = content ? content.replace(/^(&nbsp;)+|(&nbsp;)+$/g, '') : '';
    const reg = /^[+-]?\d+(\.\d+)?$/;//可选正负号开头，其余是合法的数字（含小数）
    let overTolerance = false;
    for (const i of selections) {
      let { basevalue, ceilfloat, floorfloat } = i;
      if (reg.test(basevalue) && reg.test(ceilfloat) && reg.test(floorfloat) && reg.test(content)) {
        let maxValue = parseFloat(basevalue) + parseFloat(ceilfloat);
        let minValue = parseFloat(basevalue) + parseFloat(floorfloat);
        let inputValue = parseFloat(content);
        if (inputValue < minValue || inputValue > maxValue) {
          overTolerance = true;
          break;
        }
      }
    }
    return overTolerance;
  }

  // 【保存】检测项
  async function saveCheckPointCheckerValue() {
    const checkItemsSelections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
    if (checkItemsSelections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
    }
    if (checkItemsSelections.length >= 2) {
      return ElMessage({ type: 'error', message: `不能同时勾选多条检测项`, grouping: true });
    }
    const selections = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();//【结果区域】勾选的数据
    if (inputCheckResultObj.checkItemResultList.length > 0 && selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测结果`, grouping: true });
    }
    const content = getCheckItemValue();
    if (!content) {
      return ElMessage({ type: 'error', message: `请在【填写区域】内先录入实测值结果`, grouping: true });
    }

    if (isOverTolerance()) {
      ElMessageBox.confirm(`所录入的检测项已超差，确认继续保存?`, '确认', { type: 'error' }).then(async () => {
        const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = checkItemsSelections[0];
        const { data, status: { msg } } = await useFetch({
          url: `${baseAPI}?actions=saveCheckResultByCheck`,
          data: {
            type: 'saveCheckResultByCheck',
            content,//录入的检测项内容
            employeename: currentUserInfo.employeename,
            childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows(),//勾选的子批次
            checkPointResult: selections,//勾选的检测项表格数据
            containerType: inputCheckResultObj.containerList[0].containertype,
            stepCheckPointId: stepcheckpointid,//检测项id
            containerId: containerid,//批次id
            containerStepWorkReportID: containerstepworkreportid,//报工id
          }
        });
        if (data.value) {
          ElMessage({ type: 'success', message: `保存成功`, grouping: true });
          clearCheckItemValue();
          await getStepCheckPointResult();
        }
      }).catch(() => {
        ElMessage({ type: 'info', message: '已取消' });
      });
    } else {
      const { containerstepworkreportid, containerid, workflowstepid, stepcheckpointid } = checkItemsSelections[0];
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=saveCheckResultByCheck`,
        data: {
          type: 'saveCheckResultByCheck',
          content,//录入的检测项内容
          employeename: currentUserInfo.employeename,
          childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows(),//勾选的子批次
          checkPointResult: selections,//勾选的检测项表格数据
          containerType: inputCheckResultObj.containerList[0].containertype,
          stepCheckPointId: stepcheckpointid,//检测项id
          containerId: containerid,//批次id
          containerStepWorkReportID: containerstepworkreportid,//报工id
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `保存成功`, grouping: true });
        clearCheckItemValue();
        const containertype = inputCheckResultObj.containerList[0].containertype;
        if (containertype !== 3) {
          await getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid: '' })
        } else {
          await getStepCheckPointResult();
        }
      }
    }
  }

  // 查询工人已录入实测值
  async function getWorkerInputValues() {
    const { containerid, containerstepworkreportid } = inputCheckResultObj.currentSelectInfo;
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=getWorkerInputValues`,
      data: {
        type: 'getWorkerInputValues',
        containerid, containerstepworkreportid
      }
    });
    return data.value;
  }

  // 【删除】检测项
  function deleteCheckPointResult() {
    const selections = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测结果`, grouping: true });
    }
    ElMessageBox.confirm(`你确认要删除吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=deleteCheckPointResult`,
        data: {
          type: 'deleteCheckPointResult',
          deleType: '1',
          checkPointResult: selections//勾选的检测项表格数据
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `删除成功`, grouping: true });
        const containertype = inputCheckResultObj.containerList[0].containertype;
        const { containerstepworkreportid } = selections[0];
        const checkItemsSelections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();//勾选的检测项
        const { containerid, workflowstepid } = checkItemsSelections[0];
        if (containertype !== 3) {
          await getCheckItemList({ containerid, workflowstepid, containerstepworkreportid, stepinfoid: '' })
        } else {
          await getStepCheckPointResult();
        }
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  // 推送三坐标
  async function sendToThreeCoordinateRecord() {
    const selections = inputCheckResultDialogCheckItemTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请勾选检测项`, grouping: true });
    }
    ElMessageBox.confirm(`你确认要推送三坐标吗?`, '确认', { type: 'warning' }).then(async () => {
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=sendToThreeCoordinateRecord`,
        data: {
          type: 'sendToThreeCoordinateRecord',
          checkPoint: selections,//勾选的检测项
          employeename: currentUserInfo.employeename,
          mainParam: inputCheckResultObj.containerList[0]//批次
        }
      });
      if (data.value) {
        ElMessage({ type: 'success', message: `推送成功`, grouping: true });
      } else {
        ElMessage({ type: 'error', message: `${msg}`, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  // 检测项导出
  async function exportCheckPointResult() {
    if (inputCheckResultObj.checkitemList.length === 0) {
      return ElMessage({ type: 'error', message: `批次没有检测项，不能导出`, grouping: true });
    }
    const { data, status: { msg } } = await useFetch({
      url: `${baseAPI}?actions=exportCheckPointItem`,
      data: {
        type: 'exportCheckPointItem',
        container: inputCheckResultObj.containerList,
        employeename: currentUserInfo.employeename,
        childContainer: inputCheckResultDialogChildContainerRef.value.getSelectionRows()//子批次
      }
    });
    if (data.value.filename) {
      ElMessage({ type: 'success', message: `导出成功`, grouping: true });
      const { filename, url } = data.value;
      fileDownload(filename, url);//下载文件
    }
  }

  function fileDownload(filename, url) {
    //通过创建a标签实现
    var link = document.createElement("a");
    link.href = url;
    //对下载的文件命名
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 检测项导入
  async function importCheckPointResult() {
    const fileCount = inputCheckResultObj.checkResultImportfileList.length;
    if (fileCount === 0) {
      return ElMessage({ type: 'error', message: `请先选择要导入的文件`, grouping: true });
    }
    if (fileCount >= 2) {
      return ElMessage({ type: 'error', message: `每次只能上传一个文件，请移除多余的文件`, grouping: true });
    }
    if (inputCheckResultObj.checkitemList.length === 0) {
      return ElMessage({ type: 'error', message: `批次没有检测项，不能导入`, grouping: true });
    }
    inputCheckResultObj.action = `../../../Ashx/InputCheckPointResultVue3PageHandler.ashx?actions=importCheckPointItem&employeename=${currentUserInfo.employeename}`;
    importCheckResultUploadRef.value.submit();
  }

  // 检测项导入成功事件
  async function handleCheckResultImportSuccess(res) {
    const { ReturnData: data, Message } = res;
    inputCheckResultObj.fileUploadList = [];
    importCheckResultUploadRef.value.clearFiles();//清空已上传的文件列表
    if (data) {
      await getStepCheckPointResult();
      ElMessage({ type: 'success', message: `导入成功`, grouping: true });
    } else {
      ElMessage({ type: 'error', message: `${Message}`, grouping: true });
    }
  }

  // 文件上传
  function uploadFileSubmit() {
    const fileCount = inputCheckResultObj.fileUploadList.length;
    if (fileCount === 0) {
      return ElMessage({ type: 'error', message: `请先选择要导入的文件`, grouping: true });
    }
    if (fileCount >= 2) {
      return ElMessage({ type: 'error', message: `每次只能上传一个文件，请移除多余的文件`, grouping: true });
    }
    const selections = inputCheckResultDialogCheckResultTableRef.value.getSelectionRows();
    if (selections.length === 0) {
      return ElMessage({ type: 'error', message: `请选择实测值结果`, grouping: true });
    }
    inputCheckResultObj.fileUploadParams.checkPointResult = JSON.stringify(selections);
    fileUploadRef.value.submit();
  }

  // 文件上传成功
  function handleFileUploadSuccess(res) {
    inputCheckResultObj.fileUploadParams.checkPointResult = [];
    const { ReturnData: data, Message } = res;
    if (data) {
      ElMessage({ type: 'success', message: `文件上传成功`, grouping: true });
    } else {
      ElMessage({ type: 'error', message: `${Message}`, grouping: true });
    }
  }

  return {
    inputCheckResultObj,
    initInputCheckResultDialogData,
    inputCheckResultDialogCheckItemTableRef,//检测项表格ref
    inputCheckResultDialogChildContainerRef,//子序号批次表格ref
    inputCheckResultDialogCheckResultTableRef,//检测项结果表格ref
    importCheckResultUploadRef,//检查项导入ref
    inputCheckResultDialogContainerTableRef,//批次表格ref
    handleCurrentChange,
    getStepCheckPointResult,//查询检测项录入结果
    saveCheckPointCheckerValue,//保存检验员录入的检测项
    deleteCheckPointResult,//删除检测项
    exportCheckPointResult,//导出检测项
    importCheckPointResult,//导入检测项
    handleCheckResultImportSuccess,//检测项导入成功事件
    checkItemRowClick,//检测项row点击事件
    copyWorkerInputValue,//一键确认（复制工人检测内容）
    sendToThreeCoordinateRecord,//推送三坐标
    fileUploadRef,//文件上传ref
    handleFileUploadSuccess,//文件上传成功事件
    uploadFileSubmit,//文件上传提交
  };
}